package admin

import (
	"github.com/gin-gonic/gin"
	"go-ecommerce/internal/model"
	"go-ecommerce/internal/service"
	"go-ecommerce/internal/utils"
	"go-ecommerce/internal/validate"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

// UpdatePermissionHandler 更新权限
func UpdatePermissionHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var req validate.UpdatePermissionRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			utils.Error(c, 401, err.Error())
			return
		}

		perm := model.Permission{
			Name:   req.Name,
			Code:   req.Code,
			Path:   req.Path,
			Method: req.Method,
		}
		if err := service.UpdatePermission(db, id, perm); err != nil {
			utils.Error(c, 401, err.Error())
			return
		}
		utils.Success(c, "更新成功")
	}
}

// DeletePermissionHandler 删除权限
func DeletePermissionHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		if err := service.DeletePermission(db, id); err != nil {
			utils.Error(c, 401, err.Error())
			return
		}
		utils.Success(c, "删除成功")
	}
}

// 获取所有的权限
func ListPermissionHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		list, err := service.GetPermissionList(db)
		if err != nil {
			utils.Error(c, 401, err.Error())
			return
		}
		utils.Success(c, "查询成功", list)
	}
}

func CreatePermissionHandler(db *gorm.DB) gin.HandlerFunc {

	return func(c *gin.Context) {
		var req validate.CreatePermissionRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			utils.Error(c, 401, err.Error())
			return
		}
		perm := model.Permission{
			Name:     req.Name,
			Code:     req.Code,
			ParentID: req.ParentID,
			Path:     req.Path,
			Method:   req.Method,
		}

		if err := service.CreatePermission(db, perm); err != nil {
			utils.Error(c, http.StatusBadRequest, err.Error())
			return
		}
		utils.Success(c, "创建成功")
	}
}

// GetAdminPermissions 获取管理员拥有的所有权限（去重）
func GetAdminPermissions(db *gorm.DB, adminID uint64) ([]model.Permission, error) {
	var roles []model.AdminRole
	err := db.Where("admin_id = ?", adminID).Find(&roles).Error
	if err != nil {
		return nil, err
	}

	var roleIDs []uint64
	for _, r := range roles {
		roleIDs = append(roleIDs, r.RoleID)
	}

	var permissionIDs []uint64
	err = db.Model(&model.RolePermission{}).Where("role_id IN ?", roleIDs).Pluck("permission_id", &permissionIDs).Error
	if err != nil {
		return nil, err
	}

	var permissions []model.Permission
	err = db.Where("id IN ?", permissionIDs).Find(&permissions).Error
	return permissions, err
}
